//
//  LaomiPlayer.m
//  LaomiKit
//
//  Created by laomi on 2020/7/21.
//  Copyright © 2020 laomi. All rights reserved.
//

#import "LaomiPlayer.h"
#import <UIKit/UIKit.h>
NSString *const Laomi_PlayerProgressChangeNotification = @"Laomi_PlayerProgressChangeNotification";
NSString *const Laomi_PlayerEndNotification = @"Laomi_PlayerEndNotification";
@interface LaomiPlayer()<AVAudioPlayerDelegate>
@property (nonatomic,assign) CGFloat        duration;//视频总时间
@property (nonatomic,assign) CGFloat        current;//当前播放时间
@property (nonatomic,strong) NSTimer        *timer;//定时器

@end


@implementation LaomiPlayer


+(instancetype)shareInstance;
{
    static dispatch_once_t onceToken;
    static id _sInstance;
    dispatch_once(&onceToken, ^{
        _sInstance = [[self alloc] init];
    });
    return _sInstance;
}


// 暂停
-(void)laomi_pause;
{
    [self.player pause];
    [self.timer invalidate];
    self.timer = nil;
    self.playStatus = LaomiPlayerStatePause;
}
// 播放
-(void)laomi_play;
{
    self.playStatus = LaomiPlayerStatePlaying;
    [self.player play];
    if (!self.timer) {
        __weak typeof(self) weakself = self;
        self.timer = [NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [weakself updateProgress];
        }];
    }
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
// 停止
-(void)laomi_stop;
{
    [self.player stop];
    [self.timer invalidate];
    self.timer = nil;
    self.playStatus = LaomiPlayerStatePause;
    
}

#pragma mark --播放结束
-(void)playWithUrl:(NSURL *)url
{
    [self.player stop];
    self.player = nil;
    [self.timer invalidate];
    self.timer = nil;
    
    
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.player.delegate = self;
    self.player.meteringEnabled = YES;
    BOOL isOK = [self.player prepareToPlay];
    if(isOK){
        [self laomi_play];
    }
}

#pragma mark --audio playler delegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [self.timer invalidate];
    self.timer = nil;
    self.playStatus = LaomiPlayerStateStoppedByPlayEnd;
    [[NSNotificationCenter defaultCenter]postNotificationName:Laomi_PlayerEndNotification object:nil];
    
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    [player pause];
}
// 中断结束的时候会调用这个方法
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
    // 一般在这个方法中继续播放音频
    [player play];
}

#pragma mark - 更新进度updateProgress
- (void)updateProgress {
    // 当前时间
    double currentTime = self.player.currentTime;
    // 展示到进度条上
    [[NSNotificationCenter defaultCenter]postNotificationName:Laomi_PlayerProgressChangeNotification object:@(currentTime)];
}

-(void)seekToTime:(CGFloat)seconds
{
    if (self.playStatus == LaomiPlayerStateStoppedByPlayEnd) {
        return;
    }
    [self.player setCurrentTime:seconds];
}
@end
